package com.fyx.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyx.config.FourthMongoConfig;
import com.fyx.config.RequestConfig;
import com.fyx.entity.*;
import com.fyx.mapper.MatchTicketInfoMapper;
import com.fyx.mapper.MatchWinEntityMapper;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.mapper.TotalTicketLotteryMapper;
import com.fyx.service.MatchService;
import com.fyx.until.DateUtil;
import com.fyx.until.HttpUtil;
import com.fyx.utils.SecurityUtils;
import com.fyx.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MatchServiceImpl  extends ServiceImpl<SysDictDetailMapper, SysDictDetail> implements MatchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = FourthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fourthMongoTemplate;

    @Autowired
    private MatchWinEntityMapper matchWinEntityMapper;

    @Autowired
    private TotalTicketLotteryMapper totalTicketLotteryMapper;

    @Override
    public Map getMatchList(Entity entity, Pageable pageable){
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if (entity.getExchangeLv()!=null&&entity.getExchangeLv()>0){
            criteria.and("exchangeLv").is(entity.getExchangeLv());
        }
        if(StringUtils.isNotEmpty(entity.getReceiver())){
            criteria.and("receiver").is(entity.getReceiver());
        }
        if(entity.getReceived()!=null){
            criteria.and("received").is(entity.getReceived());
        }
        if(entity.getQTime()!=null){
            criteria.andOperator(Criteria.where("time").gte(entity.getQTime().get(0).getTime()/1000).lte(entity.getQTime().get(1).getTime()/1000));
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"create_time"}));
        List<Entity> list = mongoTemplate.find(query, Entity.class,"entity");
        if(list.size()>0){
            for (Entity entity1:list){
                Integer j=0;
               if(entity1.getConsume_good_list().size()>0){
                   for(int i=0;i<entity1.getConsume_good_list().size();i++){
                     Map st=(Map)entity1.getConsume_good_list().get(i);
                       j+= Convert.toInt(st.get("num"));
                     // j+=st.get("num");
                   }
               }
               entity1.setGoodsNum(j);
               entity1.setGoodsId("奖券");
            }
        }
        long total = mongoTemplate.count(query, "entity");
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public Map getMatchTurnWin(MatchWinEntity matchWinEntity, Pageable pageable){
        Page<MatchWinEntity> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<MatchWinEntity> wrapper=new QueryWrapper<>();
        if(matchWinEntity.getQTime()!=null){
            wrapper.ge("time",matchWinEntity.getQTime().get(0).getTime()/1000);
            wrapper.le("time",matchWinEntity.getQTime().get(1).getTime()/1000);
        }
        wrapper.eq("channel","total");
        wrapper.orderBy(true,false,"time");
        IPage<MatchWinEntity> ipage = matchWinEntityMapper.selectPage(page,wrapper);
        List<MatchWinEntity> list=ipage.getRecords();
        if(list.size()>0){
            for(MatchWinEntity matchWinEntity1:list){
                matchWinEntity1.setSettlements(Convert.toIntArray(matchWinEntity1.getSettlement().split(",")));
            }
        }
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",ipage.getTotal());
        return map;
    }

    @Override
    public List<MatchWinEntity> getMatchTurnWinMore(Integer time,String channel){
        QueryWrapper<MatchWinEntity> wrapper =new QueryWrapper<>();
        if(time!=null&&time>0){
            wrapper.eq("time",time);
            wrapper.eq("father_channel",channel);
        }
        wrapper.orderBy(true,false,"id");
        List<MatchWinEntity> list = matchWinEntityMapper.selectList(wrapper);
        if(list.size()>0){
            for(MatchWinEntity matchWinEntity:list){
                matchWinEntity.setHasChildren(false);
                matchWinEntity.setSettlements(Convert.toIntArray(matchWinEntity.getSettlement().split(",")));
            }
        }
        return list;
    }
    @Override
    public Boolean editMatchReceive(Entity entity){
        Update update=new Update();
        if(StringUtils.isNotEmpty(entity.getId())){
            update.set("update_id", SecurityUtils.getCurrentUsername());
            update.set("update_time",new Date().getTime()/1000);
            update.set("card",entity.getCard());
            update.set("received",2);
            fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(entity.getId())), update, "entity");
            Thread t = new Thread(new Runnable() {
                public void run() {
                        if(!entity.getReceiver().equals("")) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("p_id", entity.getReceiver());
                            jsonObject.put("title", "兑换物品消息");
                            if(entity.getName().indexOf("京东卡")>0){
                                jsonObject.put("content", "尊敬的玩家您好，您兑换的"+entity.getName()+"，兑换密码为:"+entity.getCard()+"。");
                            }else{
                            jsonObject.put("content", "尊敬的玩家您好，您兑换的"+entity.getName()+"已成功发放，由于运营商不同到账可能有延迟，请稍等！");}
                            jsonObject.put("mail_type", 3);
                            JSONObject map = new JSONObject();
                            map.put("cmd", "send_mail");
                            map.put("args", jsonObject);
                            try {
                                HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

            });
            t.start();
            return true;
        }
        return  false;
    }

    @Autowired
    private MatchTicketInfoMapper matchTicketInfoMapper;

    @Override
    public Map getMatchTicketLotteryList(TotalTicketLottery totalTicketLottery, Pageable pageable){
        Page<TotalTicketLottery> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<TotalTicketLottery> wrapper=new QueryWrapper<>();
        if(totalTicketLottery.getQTime()!=null){
            wrapper.ge("time",totalTicketLottery.getQTime().get(0).getTime()/1000);
            wrapper.le("time",totalTicketLottery.getQTime().get(1).getTime()/1000);
        }
        wrapper.eq("channel","total");
        wrapper.eq("flag",totalTicketLottery.getFlag());
        wrapper.orderBy(true,false,"time");
        IPage<TotalTicketLottery> ipage = totalTicketLotteryMapper.selectPage(page,wrapper);
        List<TotalTicketLottery> list=ipage.getRecords();
        if(list.size()>0){
            for(TotalTicketLottery totalTicketLottery1:list){
                totalTicketLottery1.setTheValue(totalTicketLottery1.getValueStr().split(","));
            }
        }
        QueryWrapper<MatchTicketInfo> wrapper2=new QueryWrapper<>();
        wrapper2.eq("flag",totalTicketLottery.getFlag());
        wrapper2.orderByDesc("time");
        Page<MatchTicketInfo> page2 = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        Map DataMaps = new HashMap();
        IPage<MatchTicketInfo> ipage2=matchTicketInfoMapper.selectPage(page2,wrapper2);
        List<MatchTicketInfo> list2= ipage2.getRecords();
        String[] yData=new String[list2.size()];;
        if(list2.size()>0) {
            for (int i = 0; i < list2.size(); i++) {
                DataMaps.put( (i+1)+"",list2.get(i).getSettlement().split(","));
                yData[i]=DateUtil.timeStamp2Date(list2.get(i).getTime() + "", "yyyy-MM-dd ").trim();
            }
        }
        Map map =new HashMap();
        map.put("content",list);
        map.put("totalElements",ipage.getTotal());
        map.put("chartData",DataMaps);
        map.put("xData",yData);
        return map;
    }

    @Override
    public List getTicketLotteryTree(Integer time,String channel,String flag){
        QueryWrapper<TotalTicketLottery> wrapper=new QueryWrapper<>();
        if(time!=null&&time>0){
            wrapper.eq("time",time);
            wrapper.eq("father_channel",channel);
            wrapper.eq("flag",flag);
        }
        wrapper.orderBy(true,false,"id");
        List<TotalTicketLottery> list= totalTicketLotteryMapper.selectList(wrapper);
        if(list.size()>0){
            for(TotalTicketLottery totalTicketLottery1:list){
                totalTicketLottery1.setTheValue(totalTicketLottery1.getValueStr().split(","));
            }
        }
        return list;
    }
}
